/*
write by wuweiwei
www.github.com/flybirdsoft

*/

var Atemplate = function(objectName, data, url){
    this.xhr = null;
    this.html = "";
    this.url = url;
    this.object = {};
    this.object.objectName = objectName;
    this.object.data = data;
}
Atemplate.prototype.ajax = function(url,callback){
    let th = this;
    this.xhr = new XMLHttpRequest();
    this.xhr.open('GET', url, true);
    this.xhr.onreadystatechange = function() {
        if (this.status == 200 && this.readyState ==4) {
            var html = this.responseText;
            callback(html);
        }
    }
    this.xhr.send();
}
/*
Atemplate.prototype.loadHtml = function(){
    this.ajax(url,function(html){
        callback(html);
    });
}
*/

Atemplate.prototype.decodeHtml = function(html){
    var reg, script,rHtml;
    reg = /<script>[\s\S]*<\/script>/;
    return html.replace(reg,"");
}

Atemplate.prototype.decodeScript = function(html){
    var reg, script,scriptString;
    reg = /<script [\s\S]*>[\s\S]*<\/script>/;
    script = reg.exec(html);

    if(!!script)
    {
        scriptString = script[0];
        if(scriptString.indexOf('<script type="module"')>-1)
        {
            this.isModule = true;
        }
        scriptString = scriptString.replace(/<script \S*>/i,"").replace("</script>","");
        //console.log(scriptString);
        return scriptString;
    }
    else
    {
        return "noScript";
    }
}

Atemplate.prototype.getScriptCode = function(html){
    let script, _ScriptCode, head;
    this._ScriptCode = this.decodeScript(html);
}

Atemplate.prototype.addScriptCode = function(){
    let _ScriptCode, script, head;
    _ScriptCode = this._ScriptCode;

    if(_ScriptCode != "noScript")
    {
        
        script = document.createElement("script");
        //script.type='text/javascript';
        script.type= !!this.isModule ? 'module' : 'text/javascript'; 
        script.text = _ScriptCode;
        head = document.getElementsByTagName("head")[0];
        head.appendChild(script);
    }
}

Atemplate.prototype.assign = function(objectName,data){
	/*
	file is string or array
	objectName is template file javascript object
	data is JSON
	*/
	this.object.objectName = objectName;
	this.object.data = data;
}

Atemplate.prototype._template = function(text,data,param){
	/*
	text is htmlTpl
	*/
	text = text.replace(/\r\n/g,"");
	var matcher = /<%=([\s\S]+?)%>|<%([\s\S]+?)%>/g;
    var index = 0; 
    var function_body = "var temp = '';";
    function_body += "temp += '";
    
    text.replace(matcher,function(match,interpolate,evaluate,offset){
        //找到第一个匹配后，将前面部分作为普通字符串拼接的表达式
        function_body += text.slice(index,offset);
        //如果是<% ... %>直接作为代码片段，evaluate就是捕获的分组
        if(evaluate){
            function_body += "';" + evaluate + "temp += '";
        }
        //如果是<%= ... %>拼接字符串，interpolate就是捕获的分组
        if(interpolate){
            function_body += "' + " + interpolate + " + '";
        }
        //递增index，跳过evaluate或者interpolate
        index = offset + match.length;
        //这里的return没有什么意义，因为关键不是替换text，而是构建function_body
        return match;
    });
    function_body += text.substr(index);
    function_body += "';return temp;";
    var render = new Function(param, function_body);
    
    return render(data);/*返回渲染的结果*/	
}

Atemplate.prototype.render = function(htmlOrCallback){
    var content, html, callback;
    var addLastLabel = function(html){
        let a,b;
    }
    if(typeof(htmlOrCallback) == "function" && !!this.url)
    {
        this.ajax(this.url, (html) => {
            this.html = html;
            content = this._template(this.html , this.object.data , this.object.objectName);
            this.getScriptCode(html);
            content = this.decodeHtml(content);
            htmlOrCallback(content);
            this.addScriptCode();
        });
    }
    else if(typeof(htmlOrCallback) == "string")
    {
        this.getScriptCode(htmlOrCallback);
        content = this._template(htmlOrCallback , this.object.data , this.object.objectName);
        setTimeout( ()=> {
            this.addScriptCode();
        },100);
    }
    return content;
}

window.Atemplate = Atemplate;

/*
try
{
    eval("export {Atemplate}");
}
catch(e)
{
    window.Atemplate = Atemplate;
    console.log("not export");
}
*/

/*
let data = [{...}]
var at = new Atemplate("items",data,"./view/*.html");
var html = at.render(function(html){
    
});
*/